<template>
  <div class="changeStyle">
    <a-modal
      title="选择人员"
      :visible="visible"
      :width="850"
      :destroyOnClose="true"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <template slot="footer">
        <div style="display: flex; justify-content: space-between">
          <div style="padding-top: 4px">
            <a-button size="small" type="link" @click="showSenior"> <a-icon type="search" />高级搜索 </a-button>
            <a-button size="small" type="link" @click="showCopy"> <a-icon type="copy" />粘贴选择 </a-button>
          </div>
          <div>
            <a-button @click="handleCancel">取消</a-button>
            <a-button key="submit" type="primary" @click="handleOk">确定</a-button>
          </div>
        </div>
      </template>
      <div style="display: flex">
        <div style="border-right: 1px solid #d8d8d8; flex: 1; padding: 0 15px">
          <a-input-search v-model="staffFrom.nameOrPhone" placeholder="搜索人员或手机号或身份证号" @search="onSearch" />
          <div @click="onCheckAll" style="cursor: pointer; margin: 5px">
            全选当页
            <i v-if="checkAll" style="font-size: 19px" class="iconfont icon-check-circle-fill primary_color"></i>
            <img v-else src="@/assets/icons/未选择.png" style="width: 18px; height: 18px" />
          </div>
          <div style="height: 420px; overflow-y: auto; padding: 0 15px">
            <div
              @click="onRow(item)"
              v-for="(item, index) in staffData"
              :key="index"
              style="cursor: pointer; height: 40px; display: flex; justify-content: space-between; align-items: center"
            >
              <span>
                <a-avatar :src="item.empPhoto" size="small" style="margin-right: 5px" icon="user" />
                {{ item.name }}{{ item.phone }}
              </span>

              <i v-if="item.isTrue" style="font-size: 19px" class="iconfont icon-check-circle-fill primary_color"></i>
              <img v-else src="@/assets/icons/未选择.png" style="width: 18px; height: 18px" />
            </div>
          </div>
          <a-pagination
            size="small"
            :total="pageCount"
            :current="staffFrom.pageNo"
            :show-total="(total) => `共 ${pageCount} 条`"
            :page-size-options="['10', '20', '50', '100']"
            @change="onChangePagination"
            @showSizeChange="showSizeChange"
          />
        </div>
        <div style="flex: 1; padding: 0 15px">
          <div style="margin-bottom: 15px">
            已选择的人员
            <span class="primary_color">{{ staffrightData.length }}人</span>

            <div style="height: 420px; overflow-y: auto; padding: 0 15px">
              <div
                v-for="(item, index) in staffrightData"
                :key="index"
                style="cursor: pointer; height: 40px; display: flex; justify-content: space-between; align-items: center"
              >
                <span>
                  <a-avatar :src="item.empPhoto" size="small" style="margin-right: 5px" icon="user" />
                  {{ item.name }}{{ item.phone }}
                </span>

                <img @click="deleteItem(item, index)" src="@/assets/icons/删除.png" style="width: 18px; height: 18px" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </a-modal>
    <a-modal
      title="适用范围-粘贴选择"
      :width="850"
      :visible="copyVisible"
      @cancel="copyVisible = false"
      @ok="copyOk"
      :destroyOnClose="true"
    >
      <div style="display: flex">
        <div style="width: 65%">
          <div style="width: 100%; height: 125px; background: #faf9f9; border-radius: 4px; padding: 14px">
            <div style="font-weight:400;color:#252525line-height:18px;font-size:16px">温馨提示</div>
            <div style="font-weight: 400; color: #999999; line-height: 18px; font-size: 12px; margin-top: 8px">
              1、在文本框内输入或批量粘贴企业在职员工身份证号，便可识别添加。
            </div>
            <div style="font-weight: 400; color: #999999; line-height: 18px; font-size: 12px; margin-top: 8px">
              2、支持识别该用工单位下的待入职、在职、已离职员工。
            </div>
            <div style="font-weight: 400; color: #999999; line-height: 18px; font-size: 12px; margin-top: 8px">
              3、支持以换行、回车、空格、逗号等符号隔开的身份证号识别
            </div>
          </div>
          <div style="margin-top: 12px">
            <a-textarea placeholder="请输入或粘贴员工身份证号" v-model="textContent" :rows="15" />
          </div>
          <div style="padding-top: 12px; display: flex; justify-content: flex-end">
            <div v-if="errorState" style="color: #ff0000; margin-right: 130px">
              <a-icon style="font-size: 16px; margin-right: 8px" type="exclamation-circle" />文本框内存在无法识别的身份证号
            </div>
            <a-button style="margin-right: 12px" @click="reset">重置</a-button>
            <a-button @click="getEmpListByIdCards" :disabled="textContent === '' || errorState">识别</a-button>
          </div>
        </div>

        <a-divider type="vertical" style="height: 480px" />
        <div style="width: 35%">
          <div>
            已选择的员工
            <span class="count">{{ chosenList.length }}人</span>
          </div>
          <div style="height: 450px; overflow: scroll">
            <div style="padding: 8px; display: flex; justify-content: space-between" v-for="(item, index) in chosenList" :key="index">
              {{ item.name }}
              <img src="@/assets/icons/删除.png" style="width: 20px; height: 20px; cursor: pointer" @click="deleteCopyItem(item)" />
            </div>
          </div>
        </div>
      </div>
    </a-modal>
    <a-modal title="适用范围-高级筛选" :width="1000" :visible="seniorVisible" @cancel="seniorCancel" @ok="seniorOk" :destroyOnClose="true">
      <div style="display: flex">
        <div style="width: 35%">
          <a-form-model :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
            <a-form-model-item label="筛选条件">
              <a-input v-model="form.nameOrPhone" placeholder="姓名/手机号" />
            </a-form-model-item>
            <a-form-model-item label="员工标签">
              <a-select mode="multiple" style="width: 100%" option-label-prop="label" v-model="form.tag">
                <a-select-option
                  v-for="(item, index) in labelList"
                  :key="`${item.tagName}_${index}`"
                  :value="item.tagName"
                  :label="item.tagName"
                  >{{ item.tagName }}</a-select-option
                >
              </a-select>
            </a-form-model-item>
            <a-form-model-item label="工作性质">
              <a-select v-model="form.postType" :options="$store.state.enums.postTypeLst" placeholder="请选择" allowClear />
            </a-form-model-item>
            <a-form-model-item label="入职日期">
              <a-range-picker
                v-model="form.joinDate"
                :placeholder="['入职开始时间', '入职结束时间']"
                class="mr12"
                @change="(e) => onDateChange(e, 'join')"
              ></a-range-picker>
            </a-form-model-item>
            <a-form-model-item label="离职日期" v-if="textState !== '批量离职'">
              <a-range-picker
                v-model="form.leaveDate"
                :placeholder="['离职日期开始时间', '离职日期结束时间']"
                @change="(e) => onDateChange(e, 'leave')"
              ></a-range-picker>
            </a-form-model-item>
            <a-form-model-item label="在职状态">
              <a-select placeholder="请选择" allowClear v-model="form.status">
                <a-select-option :key="1" :value="1">待入职</a-select-option>
                <a-select-option :key="2" :value="2">在职</a-select-option>
                <a-select-option :key="4" :value="4">已离职</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-form-model>
          <div style="display: flex; justify-content: center">
            <a-button @click="clearForm">重置</a-button>
            <a-button type="primary" style="margin-left: 8px" @click="getSeniorListCheck">查询</a-button>
            <!-- getSeniorListCheck -->
          </div>
        </div>
        <a-divider type="vertical" style="height: 480px" />
        <div style="width: 40%">
          <a-table
            :columns="columns"
            :data-source="dataList"
            :pagination="pagination"
            @change="handleTableChange"
            :scroll="{ x: 500 }"
            row-key="id"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          ></a-table>
        </div>

        <a-divider type="vertical" style="height: 480px" />
        <div style="width: 25%">
          <div>
            已选择的员工
            <span class="count">{{ seniorList.length }}人</span>
          </div>
          <div style="height: 450px; overflow: scroll">
            <div style="padding: 8px; display: flex; justify-content: space-between" v-for="(item, index) in seniorList" :key="index">
              {{ item.name }}
              <img src="@/assets/icons/删除.png" style="width: 20px; height: 20px; cursor: pointer" @click="deleteSeniorItem(item)" />
            </div>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>
<script>
import { selectAllByEmpInfoQuery, selectAllByCompanyIdAndIdCard } from "../info/component/api.js";
import { listByCompanyIdGet, delEmpInfoBatchReq } from "../info/api";
const columns = [
  { title: "姓名", dataIndex: "name", key: "name", width: 80 },
  { title: "手机号", dataIndex: "phone", key: "phone", width: 120 },
  { title: "身份证号", dataIndex: "idCard", key: "idCard", width: 200 }
];
export default {
  components: {},
  data() {
    return {
      companyName: this.$store.state.hr.companyName,
      companyId: this.$store.state.hr.companyId,
      postTypeShow: true,
      options: [],
      probationDays: null,
      selectedRows: [],
      // companyId: this.$store.state.hr.companyId,
      labelList: [],
      textState: "",
      columns,
      dataList: [],
      seniorVisible: false,
      seniorList: [],
      selectedRowKeys: [],
      labelCol: { span: 7 },
      wrapperCol: { span: 16 },
      form: {},
      pagination: {
        pageSize: 10,
        total: 0,
        size: "small",
        current: 1,
        showTotal: (total) => `共 ${total} 条`
      },
      // //////////////////
      chosenList: [],
      textContent: "",
      copyVisible: false,
      errorState: false,
      // ///////////////////////////
      checkAll: false,
      visible: false,
      staffFrom: {
        companyId: this.$store.state.hr.companyId,
        nameOrPhone: null,
        pageNo: 1,
        pageSize: 10
      },
      pageCount: 0,
      staffData: [],
      staffrightData: [],
      confirmLoading: false,
      spinning: false
    };
  },
  watch: {
    textContent(e) {
      if (e) {
        this.errorState = false;
      }
    }
  },
  methods: {
    handleBatchFunc(list) {
      const ids = list.map((item) => item.id);
      this.$confirm({
        title: "删除确认",
        content: "删除后将无法恢复，确认要删除选中的员工吗？",
        onOk: () => {
          delEmpInfoBatchReq(ids)
            .then((res) => {
              this.$message.success("删除成功");
              this.$emit("saveOk1");
            })
            .catch((err) => {
              console.log(err);
            });
        },
        onCancel: () => {}
      });
    },
    handleOk(e) {
      if (this.staffrightData.length === 0) {
        this.$message.error("请您勾选人员后点击确定");
        return;
      }
      this.confirmLoading = true;
      this.visible = false;

      this.handleBatchFunc(this.staffrightData);
      this.confirmLoading = false;
    },
    copyOk() {
      if (this.chosenList.length === 0) {
        this.$message.error("请您勾选人员后点击确定");
        return;
      }
      this.copyVisible = false;
      this.handleBatchFunc(this.chosenList);
    },
    seniorOk() {
      if (this.seniorList.length === 0) {
        this.$message.error("请您勾选人员后点击确定");
        return;
      }
      this.seniorVisible = false;
      // 批量离职返回上一页，批量确认离职 去新弹出框
      this.handleBatchFunc(this.seniorList);
    },
    deleteSeniorItem(e) {
      this.seniorList.forEach((item, index) => {
        if (item.id === e.id) {
          this.seniorList.splice(index, 1);
          this.selectedRowKeys.forEach((item2, index2) => {
            if (item2 === e.id) {
              this.selectedRowKeys.splice(index2, 1);
            }
          });
        }
      });
    },
    onDateChange(e, text) {
      console.log(e, text);
      if (text === "join") {
        this.form.joinDateStart = e.length !== 0 ? e[0].format("YYYY-MM-DD") : null;
        this.form.joinDateEnd = e.length !== 0 ? e[1].format("YYYY-MM-DD") : null;
      } else {
        this.form.leaveDateStart = e.length !== 0 ? e[0].format("YYYY-MM-DD") : null;
        this.form.leaveDateEnd = e.length !== 0 ? e[1].format("YYYY-MM-DD") : null;
      }
    },
    onSelectChange(selectedRowKeys, e) {
      this.selectedRowKeys = selectedRowKeys;
      this.dataList.forEach((item) => {
        selectedRowKeys.forEach((item2) => {
          if (item.id === item2) {
            this.seniorList.push(item);
            this.seniorList = this.unique(this.seniorList);
          }
        });
      });
      this.seniorList.forEach((item, index) => {
        if (this.selectedRowKeys.indexOf(item.id) === -1) {
          item.isSelectedItem = 2;
        }
      });
      var arr = [];
      this.seniorList.forEach((item, index) => {
        if (!item.isSelectedItem) {
          arr.push(item);
        }
      });
      this.seniorList = JSON.parse(JSON.stringify(arr));
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      // this.checkStatue = 0;
      this.getSeniorList();
    },
    clearForm() {
      this.form = {
        companyId: this.companyId,
        nameOrPhone: null,
        pageNo: 1,
        pageSize: 10
      };
    },
    seniorCancel() {
      this.seniorVisible = false;
      this.selectedRowKeys = [];
    },
    getSeniorListCheck() {
      this.pagination.pageSize = 10;
      this.pagination.current = 1;
      this.checkStatue = 1;
      this.getSeniorList();
    },
    getListByCompanyId() {
      listByCompanyIdGet({ companyId: this.companyId })
        .then(({ data }) => {
          this.labelList = data;
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    showSenior() {
      this.visible = false;
      this.seniorVisible = true;
      this.pagination = {
        pageSize: 10,
        total: 0,
        size: "small",
        current: 1,
        showTotal: (total) => `共 ${total} 条`
      };
      this.form = {
        companyId: this.companyId,
        nameOrPhone: null,
        pageNo: 1,
        pageSize: 10
      };
      this.selectedRowKeys = [];
      this.getSeniorList();
      this.getListByCompanyId();
      if (this.staffrightData.length > 0) {
        this.seniorList = JSON.parse(JSON.stringify(this.staffrightData));
        this.staffrightData.forEach((item, index) => {
          this.selectedRowKeys.push(item.id);
        });
      } else {
        this.selectedRowKeys = [];
        this.seniorList = [];
      }
    },
    getSeniorList() {
      const data = {
        // ...this.staffFrom,
        ...this.form,
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize
      };
      let fun = "";
      fun = selectAllByEmpInfoQuery(data);
      fun
        .then((res) => {
          if (res.data === null || res.data.entities === null) {
            this.total = 0;
            this.pagination.total = 0;
            this.dataList = [];
          } else {
            this.pagination.total = res.data && res.data.entityCount;
            this.dataList = res.data.entities;
          }
        })
        .catch((err) => {
          console.log("err==>", err);
        });
    },
    // `````````高级粘贴```````````
    deleteCopyItem(e) {
      this.chosenList.forEach((item, index) => {
        if (item.id === e.id) {
          this.chosenList.splice(index, 1);
        }
      });
    },
    showCopy() {
      this.visible = false;
      this.textContent = "";
      this.copyVisible = true;
      if (this.staffrightData.length > 0) {
        this.chosenList = JSON.parse(JSON.stringify(this.staffrightData));
      } else {
        this.chosenList = [];
      }
    },
    getEmpListByIdCards() {
      if (this.textContent !== "") {
        const arr = this.textContent.split(/[\W]/);
        let fun = "";
        const data = {
          cardList: arr,
          companyId: this.companyId
        };
        fun = selectAllByCompanyIdAndIdCard(data);
        fun.then((res) => {
          // console.log(res)
          const obj = {};
          if (this.staffrightData.length > 0) {
            this.chosenList = [...this.staffrightData, ...this.chosenList, ...res.data.empInfoListVOList].reduce((cur, next) => {
              obj[next.id] ? "" : (obj[next.id] = true && cur.push(next));
              return cur;
            }, []);
            this.chosenList = this.unique(this.chosenList);
          } else {
            this.chosenList = [...this.chosenList, ...res.data.empInfoListVOList].reduce((cur, next) => {
              obj[next.id] ? "" : (obj[next.id] = true && cur.push(next));
              return cur;
            }, []);
          }
          this.textContent = res.data.idCardList.join(",");
          if (res.data.idCardList.length > 0) {
            this.$nextTick(() => {
              this.errorState = true;
            });
          }
        });
      }
    },
    // showModal(e) {
    //   console.log("companyName", e);
    //   this.selectedRows = e;
    //   this.visible = true;
    //   this.getCompanyId();
    // },
    unique(arr) {
      const res = new Map();
      return arr.filter((arr) => !res.has(arr.id) && res.set(arr.id, 1));
    },
    reset() {
      this.textContent = "";
      this.errorState = false;
    },
    // ··········选择人员·······························

    // 全选当前页面
    onCheckAll() {
      this.checkAll = !this.checkAll;
      // console.log(this.checkAll,this.staffData)
      if (this.checkAll) {
        this.staffData.forEach((element) => {
          if (!element.isTrue) {
            this.onRow(element);
          }
        });
      } else {
        this.staffData.forEach((element) => {
          if (element.isTrue) {
            this.staffrightData.forEach((esy, index) => {
              if (esy.id === element.id) {
                this.deleteItem(element, index);
              }
            });
          }
        });
      }
    },
    deleteItem(item, index) {
      this.staffrightData.splice(index, 1);
      this.staffData.forEach((element) => {
        if (element.id === item.id) {
          element.isTrue = false;
          this.checkAll = false;
        }
      });
    },
    onSearch() {
      this.staffFrom.pageNo = 1;
      this.getPrePersonnelFun();
    },
    onChangePagination(pageNumber) {
      this.staffFrom.pageNo = pageNumber;
      this.getPrePersonnelFun();
    },
    showSizeChange(current, size) {
      this.staffFrom.pageNo = 1;
      this.staffFrom.pageSize = size;
      this.getPrePersonnelFun();
    },
    onRow(item) {
      item.isTrue = !item.isTrue;
      if (item.isTrue) {
        let num = 0;
        this.staffData.forEach((element) => {
          if (element.isTrue) {
            num += 1;
          }
        });
        this.checkAll = this.staffData.length === num;

        const arr = this.staffrightData.filter((items) => items.id === item.id);
        if (arr.length === 0) {
          this.staffrightData.push(item);
        }
      } else {
        this.checkAll = false;
        this.staffrightData.forEach((element, index) => {
          if (item.id === element.id) {
            this.staffrightData.splice(index, 1);
          }
        });
      }
    },
    getPrePersonnelFun() {
      const data = {
        ...this.staffFrom
      };
      let fun = "";
      fun = selectAllByEmpInfoQuery(data);
      fun
        .then((res) => {
          if (res.data) {
            if (res.data.entities) {
              res.data.entities.forEach((element, index) => {
                res.data.entities[index].isTrue = false;
              });
            }

            this.staffrightData.forEach((element) => {
              res.data.entities.forEach((esy) => {
                if (element.id === esy.id) {
                  esy.isTrue = true;
                }
              });
            });
          }
          this.staffData = res.data ? res.data.entities : [];
          this.pageCount = res.data ? res.data.entityCount : 0;
          const arr = this.staffData.filter((item) => item.isTrue);
          this.checkAll = !!(arr.length === this.staffData.length && arr.length !== 0);
        })
        .catch((err) => {
          console.log("err==>", err);
        });
    },
    showModal(e) {
      this.visible = true;
      this.textState = e;
      this.staffFrom = {
        companyId: this.companyId,
        nameOrPhone: null,
        pageNo: 1,
        pageSize: 10
      };
      this.staffrightData = [];
      this.getPrePersonnelFun();
    },
    handleCancel(e) {
      this.visible = false;
    }
  }
};
</script>
<style lang="scss" scoped>
.postTypeL {
  display: flex;

  flex-direction: row;
  align-items: center;
}
.changeStyleText {
  position: absolute;
  top: 20px;
  left: 86px;
  font-size: 12px;
  color: #767885;
}
.employee-selector {
  height: 410px;
  margin-top: 2px;
  padding-right: 10px;
  margin-bottom: 10px;
  overflow: auto;
}
.verticalBar {
  width: 1px;
  background: #e8e8e8;
  display: inline-block;
  margin-top: 40px;
  vertical-align: top;
  margin-right: 30px;
  margin-left: 30px;
  html,
  body,
  #app {
    height: 100%;
  }
}
.tree-item {
  display: flex;
  justify-content: space-between;
  flex-direction: row;
  align-items: center;
  cursor: pointer;
  margin-top: 10px;
}
.tree-item2 {
  display: flex;
  flex-direction: row;
  align-items: center;
  cursor: pointer;
  // margin-top: 10px;
  margin-bottom: 10px;
}
.employee-selector-wrapper2 {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  .employee-selector-block {
    width: 400px;
    .employee-selector-title {
      width: 100%;
      height: 32px;
      line-height: 32px;
      font-size: 14px;
    }
    .employee-selector {
      height: 400px;
      margin-top: 20px;
      padding-right: 20px;
      overflow: auto;
      .employee-selector-item {
        width: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
      }
    }
  }
  .employee-selector-block2 {
    width: 400px;
    .employee-selector-title {
      width: 100%;
      height: 32px;
      line-height: 32px;
      font-size: 14px;
    }
    .employee-selector {
      height: 500px;
      margin-top: 20px;
      padding-right: 10px;
      overflow: auto;
      .employee-selector-item {
        width: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
      }
    }
  }
}
.iconStyle {
  margin-left: 10px;
  font-size: 18px;
  color: var(--primary);
}
</style>
